package world.zwq.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import net.sf.jsqlparser.statement.select.KSQLJoinWindow;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import world.zwq.common.utils.PageUtils;
import world.zwq.common.utils.Query;

import world.zwq.gulimall.product.dao.CategoryDao;
import world.zwq.gulimall.product.entity.CategoryEntity;
import world.zwq.gulimall.product.service.CategoryBrandRelationService;
import world.zwq.gulimall.product.service.CategoryService;
import world.zwq.gulimall.product.vo.Catalog2Vo;

import javax.xml.datatype.Duration;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    private static Map<String, Object> cache = new HashMap<>();

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构

        //1）找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map(menu -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> menu1.getSort() == null || menu2.getSort() == null ? 1 : menu1.getSort() - menu2.getSort()).collect(Collectors.toList());
        //2)找到所有以及分类子分类

        return level1Menus;
    }

    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> allList) {
        List<CategoryEntity> list = allList.stream().filter(menu -> entity.getCatId().equals(menu.getParentCid())).map(menu -> {
            menu.setChildren(getChildren(menu, allList));
            return menu;
        }).sorted((menu1, menu2) -> menu1.getSort() == null || menu2.getSort() == null ? 1 : menu1.getSort() - menu2.getSort()).collect(Collectors.toList());
        return list;
    }

    @Override
    public void removeMenusByIds(List<Long> catIds) {
        /*
         * TODO: 1、检查当前删除的菜单，是否被别的地方引用
         */
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * @CacheEvict：失效模式
     * 1、同时使用多种缓存操作 @Caching
     * 2、指定删除某个分区下的所有数据 @CacheEvict(value = "category",allEntries = true)
     * 3、存储同一个义务类型数据，都指定成同一个分区
     * @param category
     */
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })

    @CacheEvict(value = "category",allEntries = true)
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            //更新品牌分类关联信息
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
        //修改缓存中的数据
        //redisTemplate.del("catalogJson");
    }

    /**
     * 自定义cache
     *   1）、指定生成的key：key属性指定，接收 SpEL
     *   2）、指定缓存的数据存活时间：配置文件中配置 ttl（time-to-live）
     *   3）、将数据序列化为json
     *      CacheAutoConfiguration -> RedisCacheConfiguration
     *      自动配置了RedisCacheManager->初始化所有的缓存 -> 每个缓存决定使用什么配置
     *      ->如果redisCacheConfiguration有就用已有的，没有就用默认配置
     *      ->想改缓存的配置，只需要给容器中加上一个redisCacheConfiguration即可
     *      ->就会应用到当前RedisCacheManager管理的所有缓存分区中
     *
     * @return
     */
    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("getLevel1Categorys,消耗时间:" + (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //查询出一级分类
        Map<String, List<Catalog2Vo>> map = entities.stream().filter(item -> item.getParentCid().equals(0L))
                .collect(
                        Collectors.toMap(k -> k.getCatId().toString(), v -> {
                            //1、每一个的以及分类，查询这个分类的2级分类
                            List<Catalog2Vo> catalog2Vos = entities.stream().filter(item -> item.getParentCid().equals(v.getCatId())).map(item -> {
                                List<Catalog2Vo.Catalog3Vo> catalog3Vos = entities.stream().filter(item1 -> item1.getParentCid().equals(item.getCatId())).map(item1 -> {
                                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), item1.getCatId().toString(), item1.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), catalog3Vos, item.getCatId().toString(), item.getName());
                                return catalog2Vo;
                            }).collect(Collectors.toList());
                            return catalog2Vos;
                        }));
        return map;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        /*
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）:解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isBlank(catalogJson)) {
            //缓存中没有数据，从数据库查询数据
            System.out.println("缓存不命中，查询数据库");
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();

            return catalogJsonFromDb;
        }
        System.out.println("缓存命中，直接返回");
        Map<String, List<Catalog2Vo>> catalogJsonFromDb = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return catalogJsonFromDb;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //分布式锁
        //锁的名字不能重复
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb = null;
        try {
            System.out.println("获取分布式锁成功");
            dataFromDb = getDataFromDb();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return dataFromDb;

    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //加锁，防止缓存击穿
        //分布式锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            //设置过期时间,必须和加锁同步
//            redisTemplate.expire("lock",300, TimeUnit.SECONDS);
            Map<String, List<Catalog2Vo>> dataFromDb = null;
            try {
                System.out.println("获取分布式锁成功");
                dataFromDb = getDataFromDb();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //删除锁，原子性，获取值对比+删除锁必须在一个原子操作下  lua脚本操作
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                //删除自己的锁
//                redisTemplate.delete("lock");
//            }
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),uuid);
            }
            return dataFromDb;
        } else {
            System.out.println("获取分布式锁成功,等待失败。。。");
            //加锁失败...重试
            //自旋的方式
            //休眠
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }

    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isNotBlank(catalogJson)) {
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return catalogJsonFromDb;
        }
        System.out.println("查询了数据库");
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //查询出一级分类
        Map<String, List<Catalog2Vo>> map = entities.stream().filter(item -> item.getParentCid().equals(0L))
                .collect(
                        Collectors.toMap(k -> k.getCatId().toString(), v -> {
                            //1、每一个的以及分类，查询这个分类的2级分类
                            List<Catalog2Vo> catalog2Vos = entities.stream().filter(item -> item.getParentCid().equals(v.getCatId())).map(item -> {
                                List<Catalog2Vo.Catalog3Vo> catalog3Vos = entities.stream().filter(item1 -> item1.getParentCid().equals(item.getCatId())).map(item1 -> {
                                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), item1.getCatId().toString(), item1.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), catalog3Vos, item.getCatId().toString(), item.getName());
                                return catalog2Vo;
                            }).collect(Collectors.toList());
                            return catalog2Vos;
                        }));
        redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(map), 1, TimeUnit.DAYS);
        return map;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLock() {

        //加锁，防止缓存击穿
        //TODO 本地锁 synchronized，JUC(lock)，在分布式场景下使用分布式锁
        synchronized (this) {
            //达到所以后，先从缓存中查询一次，如果没有才需要继续查询
            return getDataFromDb();

        }
    }
}